<template>
  <q-dialog v-model="visible">
    <q-card style="max-height: calc(100vh - 2rem);  overflow-x: hidden">
      <q-card-section class="text-h6">{{
          modify ? '修改' : '新增'
        }}运输订单
      </q-card-section>
      <q-separator/>
      <div style="max-height: calc(100vh - 10rem); overflow-y: auto">
        <q-card-section class="q-gutter-sm q-pa-md">
          <q-input v-if="modify" v-model="order.id" outlined label="订单ID"
                   readonly/>
          <q-input v-if="modify" v-model="order.status" outlined
                   label="订单状态" readonly/>
          <q-select
              outlined style="min-width: 10rem" behavior="menu"
              v-model="order.type" clearable
              :options="typeOption"
              label="订单类型"
              emit-value
              map-options
          />
          <q-slide-transition>
            <q-select
                v-if="modelOption.length !== 0" behavior="menu"
                outlined style="min-width: 10rem"
                v-model="order.model"
                :options="modelOption"
                label="机器人型号"
                emit-value
                map-options
            />
          </q-slide-transition>
          <q-input v-if="order.taskID != null" v-model="order.taskID" outlined
                   label="所属任务ID" readonly/>
          <q-slide-transition>
            <div v-if="order.type === 'transport-lift'"
                 class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm">
              <div class="text-subtitle1 text-bold">顶升工位信息</div>
              <map-pose-selector filled v-model="order.startPose"
                                 label="取货工位" filter="station-lift"/>
              <map-pose-selector filled v-model="order.targetPose"
                                 label="送货工位"/>
            </div>
            <div v-else-if="order.type === 'transport-cargo'"
                 class="q-gutter-y-sm">
              <div
                  class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm">
                <div class="text-subtitle1 text-bold">配送订单信息</div>
                <q-input v-model="order.receiverPhone" label="接收人手机号"/>
                <q-input v-model="order.priority" label="订单优先级"
                         type="number" max="5" min="1"/>
              </div>
              <div
                  class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm">
                <div class="text-subtitle1 text-bold">目的地信息</div>
                <map-pose-selector filled v-model="order.startPose"
                                   label="取货点"/>
                <map-pose-selector filled v-model="order.targetPose"
                                   label="送货点"/>
              </div>
            </div>
            <div v-else-if="order.type === 'transport-as-rs'"
                 class="q-gutter-y-sm">
              <div
                  class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm">
                <div class="text-subtitle1 text-bold">取货目的地信息</div>
                <q-input filled label="目标接驳台层数"
                         v-model="order.sender.level" type="number"/>
                <q-input filled label="货物规格" v-model="order.sender.specs"/>
                <map-pose-selector filled v-model="order.sender.poseID"
                                   label="取货点" filter="station-port"/>
              </div>
              <div
                  class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm">
                <div class="text-subtitle1 text-bold">放货目的地信息</div>
                <q-input filled label="目标接驳台层数"
                         v-model="order.receiver.level" type="number"/>
                <q-input filled label="货物规格"
                         v-model="order.receiver.specs"/>
                <map-pose-selector filled v-model="order.receiver.poseID"
                                   label="送货点" filter="station-port"/>
              </div>
            </div>
            <div v-else-if="order.type === 'transport-fork'">
              <shelf-selector v-model="order.startPose" label="取货货架"/>
              <shelf-selector class="q-mt-sm" v-model="order.targetPose"
                              label="放货货架"/>
            </div>
            <div v-else-if="order.type === 'transport-catch'"
                 class="q-gutter-y-sm">
              <div
                  class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm"
                  v-if="order.sender">
                <div class="text-subtitle1 text-bold">取货目的地信息</div>
                <div class="row q-gutter-x-sm">
                  <add-catch-sender v-model="order.sender"/>
                  <catch-sender-list v-model="order.sender"/>
                </div>
              </div>
              <div
                  class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm"
                  v-if="order.receiver">
                <div class="text-subtitle1 text-bold">放货目的地信息</div>
                <map-pose-selector filled v-model="order.receiver.poseID"
                                   label="放货工位点" filter="catch"/>
                <posture-selector filled v-model="order.receiver.posture"/>
                <q-input filled v-model="order.receiver.count" label="数量"/>
                <q-input filled v-model="order.receiver.specs" label="规格"/>
              </div>
              <q-input v-model="order.priority" class="q-mt-sm" label="优先级"
                       outlined type="number" max="5" min="1"/>
            </div>
          </q-slide-transition>
        </q-card-section>
        <template
            v-if="modify && ['未分配','取件中','配送中'].includes(order.status)">
          <q-separator/>
          <q-card-section class="q-gutter-y-sm">
            <div class="text-subtitle1">分配至机器人</div>
            <amr-selector outlined v-model="device" :defaultType="order.type"/>
            <q-btn stretch color="primary" :disable="device === ''"
                   class="full-width" label="立即执行"
                   @click="execute(device)"/>
          </q-card-section>
        </template>
      </div>
      <q-separator/>
      <q-slide-transition v-if="modify">
        <q-card-section class="q-pa-none row" v-if="modified">
          <q-btn stretch color="primary" class="col" label="修改订单"
                 @click="update"/>
          <q-btn stretch color="secondary" class="col" label="还原修改"
                 @click="reset"/>
        </q-card-section>
        <q-card-section class="q-pa-none row" v-else>
          <q-btn stretch color="negative" class="col" label="删除订单"
                 @click="remove"/>
        </q-card-section>
      </q-slide-transition>
      <q-slide-transition v-else>
        <div v-show="!incomplete" class="bg-primary">
          <q-btn unelevated class="full-width text-subtitle1 text-bold"
                 color="primary" label="新增订单" @click="update"/>
        </div>
      </q-slide-transition>
    </q-card>
  </q-dialog>
</template>

<script setup>
import {ref, computed, watch} from 'vue'
import {useQuasar} from 'quasar'
import {useAPIStore} from 'stores/api'
import {api} from 'boot/axios'

import ShelfSelector from 'components/transport/shelf/ShelfSelector.vue'
import MapPoseSelector from 'components/mapPose/pose/MapPoseSelector.vue'
import AmrSelector from 'components/actionPlan/AmrSelector.vue'
import PostureSelector
  from 'components/transport/catch/posture/PostureSelector.vue'
import AddCatchSender
  from 'components/transport/orders/catch/AddCatchSender.vue'
import CatchSenderList
  from 'components/transport/orders/catch/CatchSenderList.vue'

const props = defineProps({
  modify: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh'])

const $q = useQuasar()
const visible = ref(false)
const device = ref('')
const origin = ref({})
const order = ref({
  id: '',
  taskID: null,
  type: '',
  targetPose: '',
  startPose: '',
  receiverPhone: '',
  status: '',
  sender: null,
  receiver: null,
  priority: 1
})
const modelOption = ref([])
const modified = computed(() => (JSON.stringify(order.value) !== JSON.stringify(origin.value)))
const type = computed(() => order.value.type)
const typeOption = [
  {
    label: '配送机器人',
    value: 'transport-cargo'
  },
  {
    label: '运输机器人（顶升）',
    value: 'transport-lift'
  },
  {
    label: '运输机器人（抓取）',
    value: 'transport-catch'
  },
  {
    label: '运输机器人（立体库）',
    value: 'transport-as-rs'
  }
]
const incomplete = computed(() => {
  if (type.value === 'transport-catch') {
    return order.value.sender.length === 0 || order.value.receiver.poseID === ''
  }
  if (type.value === 'transport-as-rs') {
    return order.value.sender.poseID === '' ||
        order.value.receiver.poseID === ''
  }
  return order.value.startPose === '' || order.value.targetPose === ''
})

watch(() => order.value.type, val => {
  if (!props.modify || modified.value) {
    order.value.model = null
    switch (val) {
      case 'transport-catch':
        order.value.sender = []
        order.value.receiver = {
          poseID: ''
        }
        break
      case 'transport-as-rs':
        order.value.sender = {
          poseID: '',
          specs: '',
          level: 1
        }
        order.value.receiver = {
          poseID: '',
          specs: '',
          level: 1
        }
        break
      default:
        order.value.sender = null
        order.value.receiver = null
    }
  }
  api.get(useAPIStore().centerUrl + 'configs/model/type/' + val).then(rs => {
    modelOption.value = rs.data
  })
})

// eslint-disable-next-line no-unused-vars
function show(data) {
  if (props.modify) {
    origin.value = data
    order.value = JSON.parse(JSON.stringify(data))
  } else {
    order.value.status = data === undefined ? '未分配' : '未开始'
    order.value.taskID = data
  }
  visible.value = true
}

function update() {
  api.put(useAPIStore().orderUrl + 'order', order.value).then(rs => {
    switch (rs.data) {
      case 'create' :
        $q.notify({
          type: 'positive',
          message: '订单新增成功'
        })
        break
      case 'modified':
        $q.notify({
          type: 'positive',
          message: '订单修改成功'
        })
        break
      default:
        $q.notify({
          type: 'negative',
          message: '操作失败'
        })
        break
    }
    emit('refresh')
    visible.value = false
  })
}

function reset() {
  order.value = JSON.parse(JSON.stringify(origin.value))
}

function remove() {
  $q.dialog({
    title: '删除订单',
    message: '是否要删除该订单？',
    cancel: true,
    persistent: true
  }).onOk(() => {
    api.delete(useAPIStore().orderUrl + 'order/' + order.value.id).then(rs => {
      emit('refresh')
      $q.notify({
        message: '订单删除成功',
        type: 'positive'
      })
      visible.value = false
    })
  })
}

function execute(data) {
  $q.dialog({
    title: '执行订单',
    message: '是否要立即执行该订单？',
    cancel: true,
    persistent: true
  }).onOk(() => {
    api.post(useAPIStore().centerUrl + 'center/send/' + data, {
      content: order.value.id,
      type: 'order'
    }).then(res => {
      console.log('-------', res)
      if (res.data === 'done') {
        $q.notify({type: "positive", message: "指令下发成功"});
      } else {
        $q.notify({type: "negative", message: "指令下发失败：" + res.data});
      }
    }).catch(err => {
      $q.notify({type: "negative", message: "指令下发失败：" + err.message});
    })
  })
}

defineExpose({
  show
})
</script>
